package org.yu.register;

import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.common.capabilities.CapabilityToken;
import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.eventbus.api.EventPriority;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import org.yu.Yu;
import org.yu.register.capability.*;

@Mod.EventBusSubscriber(bus = Mod.EventBusSubscriber.Bus.FORGE,modid = Yu.MODID)
public class CapabilityRegister {
    public static final Capability<LingQiStorage> LING_QI_STORAGE= CapabilityManager.get(new CapabilityToken<>() {});
    public static final Capability<LingQi> LING_QI= CapabilityManager.get(new CapabilityToken<>() {});
    public static final Capability<ItemMixedCapability> MIXED_ITEM =CapabilityManager.get(new CapabilityToken<>(){});
    public static final Capability<MultiDustCapability> MULTI_DUST =CapabilityManager.get(new CapabilityToken<>(){});
    @SubscribeEvent
    public static void onRegisterCapabilities(RegisterCapabilitiesEvent event) {
        event.register(LingQiStorage.class);
        event.register(LingQi.class);
        event.register(ItemMixedCapability.class);
        event.register(MultiDustCapability.class);
    }

    @SubscribeEvent
    public static void playerClone(PlayerEvent.Clone evt) {
        Player player = evt.getPlayer();
        Player oldPlayer = evt.getOriginal();
        oldPlayer.revive();
        LazyOptional<LingQi> oldHandler = oldPlayer.getCapability(CapabilityRegister.LING_QI);
        LazyOptional<LingQi> newHandler = player.getCapability(CapabilityRegister.LING_QI);
        oldHandler.ifPresent(
                oldLingQi -> newHandler.ifPresent(lingQi -> lingQi.deserializeNBT(oldLingQi.serializeNBT())));
    }
    @SubscribeEvent
    public static void entityCapabilityInit(AttachCapabilitiesEvent<Entity> event) {
        var entity=event.getObject();
        if(entity instanceof LivingEntity livingEntity)
            event.addCapability(new ResourceLocation(Yu.MODID,"entity_ling_qi"),new LingQiProvider(livingEntity));
    }
}
